package utils;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;

import model.TableInformation;

public class ArrayUtils {

	public static int indexOf(int[] arr, int val) {
		for (int i = 0; i < arr.length; i++) {
			if (arr[i] == val)
				return i;
		}
		return -1;
	}
	
	public static String[] translateIdArrayToStringArray(Object[] ids, TableInformation table_info) {
		String[] output = new String[ids.length];
		for (int i = 0; i < ids.length; i++) {
			output[i] = table_info.getStringForId((Integer)(ids[i]));
			if (output[i] == null) {
				System.out.println((Integer)(ids[i]));
			}
		}
		return output;
	}
	
	public static Pair<String[], double[]> sortPairedArrays(String[] strings, double[] probs) {
		ArrayList<Pair<String, Double> > list = new ArrayList<Pair<String, Double> >();
		for (int i = 0; i < strings.length; i++) {
			list.add(new Pair<String, Double>(strings[i], probs[i]));
		}
		Collections.sort(list, new Comparator<Pair<String, Double> >()
		        {
		            public int compare(Pair<String, Double>o1,
		            		Pair<String, Double> o2)
		            {
		                    return o2.getSecond().compareTo(o1.getSecond());
		            }
		        });
		String[] sorted_strings = new String[strings.length];
		double[] sorted_probs = new double[probs.length];
		Iterator<Pair<String, Double> > it = list.iterator();
		for (int i = 0; i < strings.length; i++) {
			Pair<String, Double> next = it.next();
			sorted_strings[i] = next.getFirst();
			sorted_probs[i] = next.getSecond();
		}
		return new Pair<String[], double[]>(sorted_strings, sorted_probs);
	}
	
	public static Pair<Object[], double[]> sortPairedArrays(Object[] objects, double[] probs) {
		ArrayList<Pair<Object, Double> > list = new ArrayList<Pair<Object, Double> >();
		for (int i = 0; i < objects.length; i++) {
			list.add(new Pair<Object, Double>(objects[i], probs[i]));
		}
		Collections.sort(list, new Comparator<Pair<Object, Double> >()
		        {
		            public int compare(Pair<Object, Double>o1,
		            		Pair<Object, Double> o2)
		            {
		                    return o2.getSecond().compareTo(o1.getSecond());
		            }
		        });
		Object[] sorted_strings = new Object[objects.length];
		double[] sorted_probs = new double[probs.length];
		Iterator<Pair<Object, Double> > it = list.iterator();
		for (int i = 0; i < objects.length; i++) {
			Pair<Object, Double> next = it.next();
			sorted_strings[i] = next.getFirst();
			sorted_probs[i] = next.getSecond();
		}
		return new Pair<Object[], double[]>(sorted_strings, sorted_probs);
	}
}
